package cn.mini.mybatis.mybatis.executor.statementHandler;

import cn.mini.mybatis.mybatis.executor.Executor;
import cn.mini.mybatis.mybatis.executor.resultset.ResultSetHandler;
import cn.mini.mybatis.mybatis.mapping.BoundSql;
import cn.mini.mybatis.mybatis.mapping.MappedStatement;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class PreparedStatementHandler extends BaseStatementHandler{


    public PreparedStatementHandler(Executor executor, MappedStatement mappedStatement,
                                    Object parameterObject, ResultSetHandler resultHandler, BoundSql boundSql) {
        super(executor, mappedStatement, parameterObject, resultHandler, boundSql);
    }
    @Override
    public Statement instantiateStatement(Connection connection) throws SQLException {
        String sql = boundSql.getSql();
        return connection.prepareStatement(sql);
    }


    @Override
    public Statement prepare(Connection connection) throws SQLException {
        String sql = boundSql.getSql();
        return connection.prepareStatement(sql);
    }


    @Override
    public void parameterize(Statement statement, BoundSql boundSql) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        ps.setInt(1,Integer.parseInt(parameterObject.toString()));
    }

    @Override
    public <E> List<E> query(Statement statement, ResultSetHandler resultHandler) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        ps.execute();
        return resultSetHandler.<E> handleResultSets(ps);
    }
}
